package com.objk.admin.security.controller;

import com.obj.commpont.common.captcha.CaptchaUtils;
import com.obj.commpont.common.captcha.util.CaptchaRandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Controller
public class VaildCodeController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/captcha/code/{uuid}")
    public void getCaptchaCode(@PathVariable String uuid, HttpServletResponse response) {
        //页面不缓存
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/png");
        try {
            String code = CaptchaRandomUtils.getCaptchaCode(4);
            redisTemplate.opsForValue().set("user:captcha:" + uuid, code, 60L * 5, TimeUnit.SECONDS);
            CaptchaUtils.createCaptchaImage(120, 40, code, "png", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
